# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""

from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QMainWindow
import http.client
import datetime
from threading import Thread
from multiprocessing import Process
#import qdarkstyle

from Ui_main import Ui_MainWindow

class Ui_MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """

        super(Ui_MainWindow, self).__init__(parent)
        self.setupUi(self)
        
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self. timer_update)
        self.cnt = 30

    @pyqtSlot()
    def on_pushButtonScan_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        self.logPrint("Unable to use yet.")
    
    @pyqtSlot()
    def on_pushButtonClrLog_clicked(self):
        """
        Slot documentation goes here.
        """
        self.textEditLog.setText("")        
        
    def SendCommand(self, cmd):
        httpClient = None
        ip = self.lineEdit_IP.text()
        self.logPrint("CMD = " + ip + ":5000" + cmd)
        try:
            httpClient = http.client.HTTPConnection(ip, 5000, timeout=30)
            httpClient.request("GET", cmd)
            response = httpClient.getresponse()
            self.logPrint(str(response.status) + " " + str(response.reason))
            #self.logPrint(str(response.read()))
        except Exception:
            self.logPrint("Failed")
        finally:
            if httpClient:
                httpClient.close()

    # print log 
    def logPrint(self, text):
        now = datetime.datetime.now()
        otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
        str = otherStyleTime + "  " + text
        self.textEditLog.append(str)
        
    @pyqtSlot()
    def on_pushButtonRecordVideo_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Video Recording ...")
        cmd = "/video_record/" + self.lineEdit_RecordTime.text() + "/" + self.lineEdit_UserID.text()
        httpClient = None
        ip = self.lineEdit_IP.text()
        self.logPrint("CMD = " + ip + ":5000" + cmd)
        try:
            httpClient = http.client.HTTPConnection(ip, 5000, timeout=30)
            httpClient.request("GET", cmd)
            response = httpClient.getresponse()
            self.logPrint(str(response.status) + " " + str(response.reason))
            #self.logPrint(str(response.read()))
            self.cnt = int(self.lineEdit_RecordTime.text())
            self.logPrint("Plase Wait " + str(self.cnt) + ' seconds ...')
            self.timer.start(1000)
        except Exception:
            self.logPrint("Failed")
        finally:
            if httpClient:
                httpClient.close()
    
    def DownloadVideo(self):
        cmd = "/video_down/" + self.lineEdit_UserID.text()
        httpClient = None
        f = open(self.lineEdit_UserID.text() + ".mp4", "wb")
        ip = self.lineEdit_IP.text()
        self.logPrint("CMD = " + ip + ":5000" + cmd)
        try:
            httpClient = http.client.HTTPConnection(ip, 5000, timeout=30)
            httpClient.request("GET", cmd)
            response = httpClient.getresponse()
            self.logPrint(str(response.status) + " " + str(response.reason))
            self.logPrint("Saving...")
            f.write(response.read())
            self.logPrint("Finished.")
        except Exception:
            self.logPrint("Failed")
        finally:
            if httpClient:
                httpClient.close()
                f.close()

    @pyqtSlot()
    def on_pushButtonDownVideo_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Video Downloading ...")
        t = Thread(target=self.DownloadVideo, name='DownVideoThread')
        t.start()
        #t.join()

    @pyqtSlot()
    def on_pushButtonPreviewVideo_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        self.logPrint("Unable to use yet.")
            
    @pyqtSlot()
    def on_pushButtonWiFiSet_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Setting Wifi ...")
        cmd = "/wifi_set/" + self.lineEdit_WiFiSSID.text() + "/" + self.lineEdit_WiFiPwd.text()
        self.SendCommand(cmd)
    
    @pyqtSlot()
    def on_pushButton_ClearVideo_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Clearing Videos Hardware ...")
        self.SendCommand("/video_clr")
    
    @pyqtSlot()
    def on_pushButton_StatusCheck_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Pi Status Check")
        self.SendCommand("/check")
    
    @pyqtSlot()
    def on_pushButton_FirmwareUpgrade_clicked(self):
        """
        Slot documentation goes here.
        """
        self.logPrint("Upgrading Firmware ...")
        self.SendCommand("/update")
    
    def timer_update(self):
        self.logPrint(str(self.cnt))
        self.cnt = self.cnt - 1
        if (self.cnt == 0):
            self.timer.stop()
            self.logPrint("Video Record Finished.")

if __name__ == '__main__':
    import sys
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    #app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    dlg = Ui_MainWindow()
    dlg.show()
    sys.exit(app.exec_())
